<template>
  <div class="question-list-page">
    <el-card shadow="never" class="toolbar">
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <span class="title">题库</span>
        <!-- 管理员添加题目按钮 -->
        <el-button 
          v-if="isAdmin" 
          type="primary" 
          @click="handleAddQuestion"
        >
          添加题目
        </el-button>
      </div>
    </el-card>

    <el-card shadow="never" class="list-card">
      <el-table
          v-loading="loading"
          :data="questionList"
          style="width: 100%"
          highlight-current-row
      >
        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column label="标题" min-width="240">
          <template #default="{ row }">
            <el-link type="primary" @click="goDetail(row.id!)">
              {{ row.title }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column label="标签" min-width="220">
          <template #default="{ row }">
            <el-tag
                v-for="(tag, i) in (row.tags || ['暂无标签'])"
                :key="i"
                size="small"
                style="margin-right: 6px; margin-bottom: 4px"
            >
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="难度" width="120" align="center">
          <template #default="{ row }">
            {{ row.title }}
          </template>
        </el-table-column>
        <el-table-column label="通过率" width="120" align="center">
          <template #default="{ row }">
            {{ row.title }}
          </template>
        </el-table-column>

        <!-- 管理员操作列 -->
        <el-table-column 
          v-if="isAdmin" 
          label="操作" 
          width="180" 
          align="center"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEditQuestion(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteQuestion(row.id!)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑题目对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="80%"
        :close-on-click-modal="false"
    >
      <div v-loading="loadingQuestion">
        <QuestionForm
            v-if="dialogVisible && !loadingQuestion"
            :question="editingQuestion"
            @submit="handleFormSubmit"
            @cancel="dialogVisible = false"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { QuestionControllerService } from '../../../generated'
import type { QuestionVO, QuestionAdminVO, QuestionAddRequest, QuestionUpdateRequest, DeleteRequest } from '../../../generated'
import { useUserStore } from '../../stores/user.ts'
import QuestionForm from './QuestionForm.vue'

const router = useRouter()
const userStore = useUserStore()

// 判断是否是管理员
const isAdmin = computed(() => {
  return userStore.user?.userRole === 'admin'
})

// —— 列表分页 —— //
const loading = ref(false)
const questionList = ref<QuestionVO[]>([])
const total = ref(0)
const pageSize = 10
const currentPage = ref(1)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加题目')
const editingQuestion = ref<QuestionAdminVO | null>(null)
const loadingQuestion = ref(false)

const fetchQuestions = async () => {
  loading.value = true
  try {
    const res = await QuestionControllerService.listQuestionVoByPage({
      current: currentPage.value,
      pageSize,
    })
    if (res.code === 0 && res.data) {
      questionList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取题目列表失败')
    }
  } catch (e) {
    ElMessage.error('网络错误，获取题目列表失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchQuestions()
}

const goDetail = (id: number) => {
  router.push({ name: 'QuestionSolve', params: { id } })
}

// 添加题目
const handleAddQuestion = () => {
  editingQuestion.value = null
  dialogTitle.value = '添加题目'
  dialogVisible.value = true
}

// 编辑题目 - 调用管理员接口获取完整信息
const handleEditQuestion = async (question: QuestionVO) => {
  if (!question.id) {
    ElMessage.error('题目ID不存在')
    return
  }
  
  loadingQuestion.value = true
  try {
    const res = await QuestionControllerService.getQuestionAdminVo(question.id)
    if (res.code === 0 && res.data) {
      editingQuestion.value = res.data
      dialogTitle.value = '编辑题目'
      dialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取题目详情失败')
    }
  } catch (e) {
    ElMessage.error('网络错误，获取题目详情失败')
  } finally {
    loadingQuestion.value = false
  }
}

// 删除题目
const handleDeleteQuestion = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这道题目吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const request: DeleteRequest = { id }
    const res = await QuestionControllerService.deleteQuestion(request)
    
    if (res.code === 0) {
      ElMessage.success('删除成功')
      fetchQuestions()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (e: any) {
    if (e !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 表单提交
const handleFormSubmit = async (formData: QuestionAddRequest | QuestionUpdateRequest) => {
  try {
    if (editingQuestion.value) {
      // 编辑
      const updateRequest: QuestionUpdateRequest = {
        id: editingQuestion.value.id,
        ...formData,
      }
      const res = await QuestionControllerService.updateQuestion(updateRequest)
      if (res.code === 0) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        fetchQuestions()
      } else {
        ElMessage.error(res.message || '更新失败')
      }
    } else {
      // 添加
      const res = await QuestionControllerService.addQuestion(formData as QuestionAddRequest)
      if (res.code === 0) {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        fetchQuestions()
      } else {
        ElMessage.error(res.message || '添加失败')
      }
    }
  } catch (e) {
    ElMessage.error('操作失败')
  }
}

onMounted(fetchQuestions)
</script>

<style scoped>
.question-list-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 16px;
}
.toolbar {
  margin-bottom: 12px;
}
.title {
  font-size: 18px;
  font-weight: 600;
}
.list-card {
  padding-bottom: 8px;
}
.pagination {
  margin-top: 12px;
  text-align: center;
}
</style>